package mysql

import (
	"campus-trade/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func Init() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	var err error
	data := appconfig.Config.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		data.User,
		data.Password,
		data.Host,
		data.Port,
		data.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据库链接成功")
	}

	err = DB.AutoMigrate(&User{}, &Class{}, &Book{}, &Comment{}, &PingLun{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据迁移成功")
	}
}
